import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums.length < 4) {
            return res;
        }
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 3; i++) {
            if (target >= 0 && nums[i] > target) {
                break;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                long twoNum = (long) nums[i] + (long) nums[j];
                if (target >= 0 && twoNum > (long) target) {
                    break;
                }
                int left = j + 1, right = nums.length - 1;
                while (left < right) {
                    long k = twoNum + (long) nums[left] + (long) nums[right];
                    if (k == (long) target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    } else if (k < (long) target) {
                        left++;
                    } else {
                        right--;
                    }
                }
                while (j < nums.length - 3 && nums[j] == nums[j + 1])
                    j++;
            }
            while (i < nums.length - 4 && nums[i] == nums[i + 1])
                i++;
        }
        return res;
    }
}
